<template>
  <div>
    <van-nav-bar
        :title="blog.title"
        left-text="返回"
        left-arrow
        @click-left="onClickLeft"
    />
    <div class="button">
      <div class="upload-demo">
        <el-upload v-if="ownBlog"
                   :before-upload="BeforeUploadVideo"
                   :http-request="UploadVideo"
                   action="">
          <el-button type="text">上传视频</el-button>
        </el-upload>
      </div>
      <el-button size="small" circle v-if="ownBlog" @click="edit(blog.id)" icon="el-icon-edit"
                 type="primary"></el-button>
      <!--      </el-link>-->
      <el-button size="small" circle v-if="ownBlog" @click="del(blog.id)" icon="el-icon-delete"
                 type="danger"></el-button>
    </div>
    <!--视频组件-->
    <video-player v-if="hasVideo" class="video-player vjs-custom-skin" ref="videoPlayer" :playsinline="true"
                  :options="playerOptions"></video-player>

    <mavon-editor
        :value="blog.content"
        defaultOpen="preview"
        :boxShadow="false"
        style="z-index:1;"
        :editable="false"
        :subfield="false"
        :toolbarsFlag="false"
    >
    </mavon-editor>

    <hr>

    <!--评论展示-->
    <ul class="comments">
      <li v-for="pcomment in comments">
        <!--通过设置一个盒子来挤过去-->

        <div @click="transportId(pcomment.cid)">
        <span class="userinfo">
          <el-avatar size="small" :src="pcomment.avatar" class="avatar"></el-avatar>
          <span class="author">{{ pcomment.author }}</span>
          </span>
          <span class="created">{{ pcomment.created }}</span>
          <p class="commentcontent">{{ pcomment.content }}</p>
        </div>

        <!--        <div class="outcomment">-->
        <!--          <a @click="transportId(pcomment.cid)">回复</a>-->
        <!--        </div>-->

        <el-drawer
            :visible.sync="drawer"
            title="轻轻的评论"
            direction="btt">
          <el-form :model="cform"
                   class="cinput">
            <el-form-item prop="content">
              <el-input
                  area
                  type="form"
                  placeholder="评论"
                  v-model="cform.content">
              </el-input>
              <el-button class="cbutton" @click="sendCcomment">回复</el-button>

            </el-form-item>
          </el-form>

        </el-drawer>

        <!--遍历子评论-->
        <ul class="ccomments">
          <li v-for="ccomment in pcomment.commentDtoList">
            <div @click="commentLast(pcomment.cid,ccomment.uid)">
              <span class="userinfo">
              <el-avatar size="small" :src="ccomment.avatar" class="avatar"></el-avatar>
              <span class="author">{{ ccomment.author }} <span v-if="ccomment.touser"> > </span> {{ccomment.touser}}</span>
              </span>
              <span class="created">{{ ccomment.created }}</span>
              <p class="commentcontent">{{ ccomment.content }}</p>
            </div>

            <el-drawer
                :visible.sync="drawer2"
                title="轻轻的评论"
                direction="btt">
              <el-form :model="cform"
                       class="cinput">
                <el-form-item prop="content">
                  <el-input
                      area
                      type="form"
                      placeholder="评论"
                      v-model="cform.content">
                  </el-input>
                  <el-button class="cbutton" @click="sendCcomment">回复</el-button>

                </el-form-item>
              </el-form>

            </el-drawer>

          </li>
        </ul>


      </li>
    </ul>

    <el-pagination class="mpage"
                   background
                   layout="prev, pager, next"
                   :current-page="currentPage"
                   :page-size="pageSize"
                   :total="total"
                   @current-change=getAllComments>
    </el-pagination>

    <h3>你好啊</h3>

    <van-tabbar class="van-tabbar">
      <slot>
        <el-form :model="pform"
                 class="input">
          <el-form-item prop="content">
            <el-input
                type="form"
                placeholder="评论"
                v-model="pform.content"
                @keyup.enter.native="sendPcomment('pform')">
            </el-input>
          </el-form-item>
        </el-form>
      </slot>
      <van-tabbar-item v-if="!isLike">
        <van-icon class="likeandcollect" name="good-job-o" size="30" color="#3D3D3DFF" @click="like"/>
      </van-tabbar-item>
      <van-tabbar-item v-if="isLike">
        <van-icon class="likeandcollect" name="good-job" size="30" color="#3D3D3DFF" @click="dislike"/>
      </van-tabbar-item>
      <van-tabbar-item v-if="!isCollected">
        <van-icon class="likeandcollect" name="star-o" size="30" color="#3D3D3DFF" @click="collect"/>
      </van-tabbar-item>
      <van-tabbar-item v-if="isCollected">
        <van-icon class="likeandcollect" name="star" size="30" color="#3D3D3DFF" @click="disCollect"/>
      </van-tabbar-item>
    </van-tabbar>
  </div>
</template>

<script>
import 'github-markdown-css'

export default {
  inject: ["reload"],
  name: "mblogdetail",
  data() {
    return {

      drawer2: false,
      uid: "",
      playerOptions: {
        playbackRates: [0.7, 1.0, 1.5, 2.0], //播放速度
        autoplay: false, //如果true,浏览器准备好时开始回放。
        muted: false, // 默认情况下将会消除任何音频。
        loop: false, // 导致视频一结束就重新开始。
        preload: "auto", // 建议浏览器在<video>加载元素后是否应该开始下载视频数据。auto浏览器选择最佳行为,立即开始加载视频（如果浏览器支持）
        language: "zh-CN",
        aspectRatio: "16:9", // 将播放器置于流畅模式，并在计算播放器的动态大小时使用该值。值应该代表一个比例 - 用冒号分隔的两个数字（例如"16:9"或"4:3"）
        fluid: true, // 当true时，Video.js player将拥有流体大小。换句话说，它将按比例缩放以适应其容器。
        sources: [
          {
            type: "video/mp4",
            src: '', //视频url地址
          },
        ],
        // poster: require("../assets/Index/video01.png"), //你的封面地址
        // width: document.documentElement.clientWidth,
        notSupportedMessage: "此视频暂无法播放，请稍后再试", //允许覆盖Video.js无法播放媒体源时显示的默认信息。
        controlBar: {
          timeDivider: true,
          durationDisplay: true,
          remainingTimeDisplay: false,
          fullscreenToggle: true, //全屏按钮
        },
      },

      hasVideo: false,

      //用于视频上传
      videoFile: new FormData(),

      drawer: false,

      ownBlog: false,   //用于是否显示编辑按钮

      blog: {
        id: "",
        title: "",
        content: "",
        avatar: "",
        author: '',
        userId: '',
      },

      //准备发送的父评论
      pform: {
        bid: '',
        content: '',
      },

      //准备发送的子评论
      cform: {
        bid: '',
        content: '',
        touserId:'',
      },

      // pcomments: {}, //父评论
      // ccomments: {},  //子评论

      comments: [],

      commentId: '',

      isLike: false,
      isCollected: false,

      //父评论分页
      currentPage: 1,
      currentPage_s: 1,
      total: 0,
      pageSize: 5,


    }
  },
  methods: {

    commentLast(pcid, uid) {
      // console.log("HHHH")
      // console.log(pcid)
      // console.log("--------"+uid)
      /*测试成功
      * 得到了最父评论id(注意不是目标评论)
      * 以及目标评论的用户id
      * */

      this.drawer2 = true
      this.commentId = pcid
      this.uid = uid

    },


    BeforeUploadVideo(file) {

      const v = file.size / 1024 / 1024 < 100
      if (!v) {
        this.$message.error('上传视频大小不能超过 100MB!')
        return false;
      }

      if (file) {
        this.videoFile.append('file', file); //  2. 上传之前，拿到file对象，并将它添加到刚刚定义的FormData对象中。
        this.$message.info("上传过程请耐心等待，成功后会自动提醒")
      } else {
        return false;
      }
    },
    UploadVideo() {
      const newData = this.videoFile;
      this.$axios.post('/videoUpload/' + this.blog.id, newData, {
        headers: {
          'Content-Type': 'multipart/ruleForm-data',
          "Authorization": localStorage.getItem("token")   //请求头携带的token
        }
      }).then(res => {
        this.$message({
          type: 'success',
          message: '上传成功'
        })
        this.reload()
      })
    },

    edit(blogId) {   //push传参
      this.$router.push({
        name: 'edit2',
        params: blogId
      })
    }
    ,
    del(blogId) {   //push传参
      this.$axios.delete('/delBlogById/' + blogId, {
        headers: {
          "Authorization": localStorage.getItem("token")
        }
      }).then(res => {
        console.log('删除成功')
        //删除成功
        this.$message({type: "success", message: "删除成功"})
        //跳转到
        this.$router.go(-1);
      })
    },


    like() {
      this.$axios.get('/likeBlog/' + this.blog.id, {
        headers: {
          "Authorization": localStorage.getItem("token")
        }
      }).then(res => {

        this.$message({type: "success", message: "点赞成功"})

        this.isLike = true

      })
    },

    dislike() {
      this.$axios.get('/dislikeBlog/' + this.blog.id, {
        headers: {
          "Authorization": localStorage.getItem("token")
        }
      }).then(res => {
        this.$message({type: "success", message: "已取消点赞"})

        this.isLike = false
      })
    },

    collect() {
      this.$axios.post('/addBlogCollection?bid=' + this.blog.id, {
        headers: {
          "Authorization": localStorage.getItem("token")
        }
      }).then(res => {
        this.$message({type: "success", message: "收藏成功"})

        this.isCollected = true
      })
    },

    disCollect() {
      this.$axios.delete('/delCollection?bid=' + this.blog.id, {
        headers: {
          "Authorization": localStorage.getItem("token")
        }
      }).then(res => {
        this.$message({type: "success", message: "已取消收藏"})

        this.isCollected = false
      })
    },

    //是否点赞或收藏
    isLikeOrCollected() {
      var blogId = this.blog.id
      //请求是否点过赞
      this.$axios.get('/isLike/' + blogId).then(res => {
        this.isLike = res.data.data.isLike
        // console.log("喜欢过吗 测试：" + this.isLike)
      })
      //请求是收藏
      this.$axios.get('/isCollected/' + blogId).then(res => {
        this.isCollected = res.data.data.isCollected
        // console.log("喜欢过吗 测试：" + this.isLike)
      })
    },

    //子评论发送
    sendCcomment() {
      //组成表单
      this.cform.parentCid = this.commentId


      console.log(this.uid)

      //表明这是最低级评论
      if(this.uid) {
        this.cform.touserId = this.uid
      }

      // console.log("parentCid = " + this.cform.parentCid)
      // console.log("content = " + this.cform.content)
      // console.log("id")
      //登录前台检测
      if (localStorage.getItem("token") == null || localStorage.getItem("token") == '') {
        //没登陆
        this.$message({
          message: '请先登录',
          type: 'warning'
        })
      } else {
        this.$axios.post('/commentChild', this.cform, {
          headers: {
            "Authorization": localStorage.getItem("token")
          }
        }).then(res => {
          this.$message({message: "回复成功", type: 'success'})
          this.reload()
          //发送完清空一下content
          this.cform.parentCid = ''
          this.commentId = ''
          this.cform.content = ''
          this.ccommentContent = ''
          this.uid = ''

        })
      }
    },

    //子评论  传输id
    transportId(id) {
      this.drawer = true
      this.commentId = id
    },

    getAllComments(currentPage) {
      this.$axios.get('/findParentComment/' + this.blog.id + "?currentPage=" + currentPage).then(res => {
        this.comments = res.data.data.records
        this.currentPage = res.data.data.current
        this.total = res.data.data.total
        this.pageSize = res.data.data.size
      })
    },

    sendPcomment(pform) {
      //登录前台检测
      if (localStorage.getItem("token") == null || localStorage.getItem("token") == '') {
        //没登陆
        this.$message({
          message: '请先登录',
          type: 'warning'
        })
      } else {
        this.$axios.post('/commentParent', this.pform, {
          headers: {
            "Authorization": localStorage.getItem("token")
          }
        }).then(res => {
          this.pform.content = ''
          this.$message({message: "评论成功", type: 'success'})
          // this.$router.push("/mblog/"+this.blog.id)
          this.reload();
        }, 5000)
      }
    },

    collectit() {
      this.isCollected = !this.isCollected
    }
    ,

    likeit() {
      this.isLike = !this.isLike
    }
    ,
    onClickLeft() {
      this.$router.push("/mindex");//返回上一层
    }
    ,
    getBlog(blogId) {
      //文章细节
      this.$axios.get('/blog/' + blogId).then(res => {
        const blog = res.data.data
        // this.blog.id = blog.id
        // // this.blog.title = blog.title
        // // this.blog.avatar = blog.avatar
        // // this.blog.author = blog.author
        // // this.blog.content = blog.content
        // // this.blog.userId = blog.userId
        this.blog = blog

        if (blog.video != null) {
          this.hasVideo = true
          this.playerOptions.sources[0].src = blog.video
        }

        //是否是自己的文章
        this.ownBlog = (this.blog.userId === this.$store.getters.getUser.id)

      })
    }
  },

  created() {
    var blogId = this.$route.params.blogId
    //设置留言的bid
    this.pform.bid = blogId
    this.blog.id = blogId
    this.getBlog(blogId)

    this.isLikeOrCollected()


    //获取父评论
    this.getAllComments(1)
  }
}
</script>

<style scoped>


.upload-demo {
  /*width: 20px;*/
  margin-left: 15px;
  margin-right: 5px;
  display: inline-block;
  text-align: left;
}

.mpage {
  margin-top: 20px;
  text-align: center;
}

h3 {
  margin-top: 50px;
  font-weight: 400;
  text-align: center;
  margin-bottom: 100px;
  color: #409EFF;
}

.outcomment {
  text-align: right;
  position: relative;
  bottom: 20px;
  color: #a8a8a8;
}

.van-tabbar {
  height: 40px;
}

.input {
  width: 80%;
}


.cinput {
  width: 90%;
  margin: auto;
}

.likeandcollect {
  margin-bottom: 5px;
}

.comments {
  width: 80%;
  margin: auto;
}

.userinfo {
  margin-right: 20px;
}

.comments > li {
  border-bottom: 1px solid rgba(82, 82, 82, 0.3);
}

.comments .created {
  font-size: 8px;
  font-weight: 400;
}

.comments .avatar {
  position: relative;
  top: 7px;
  margin-right: 5px;
}

.childcomments {
  margin-left: 40px;
}

.childcomments li {
  border-top: 1px solid rgba(82, 82, 82, 0.3);
  margin-bottom: 3px;
}

.goleft {
  display: inline-block;
  width: 25%;
}

.ccomments {
  position: relative;
  left: 50px;
}

.cbutton {
  margin-top: 30px;
  text-align: right;
}

.button {
  text-align: left;
  margin-right: 20px;
}

</style>